package com.sz.app;

import com.sz.common.base.logger.Logger;
import com.sz.common.base.utils.BeanUtils;
import com.sz.common.core.service.thread.RunnableBean;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

import java.util.List;
import java.util.concurrent.*;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: qiankun<br>
 * Date: 2017-06-29 20:24:00
 */
public class ApplicationStartupListener implements ApplicationListener<ApplicationReadyEvent> {

    //本类不是bean，不能自动注入其它bean
    protected Logger logger = Logger.getLogger(this.getClass());

    ExecutorService cachedThreadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        logger.debug("Application is Ready");
        List<RunnableBean> beans = BeanUtils.getBeansByType(RunnableBean.class);
        if (beans != null && beans.size() > 0) {
            for (RunnableBean bean : beans) {
                logger.debug("Ready to start thread " + bean.getName());
                cachedThreadPool.execute(bean);
            }
        }
    }
}
